package com.example.myeventbus;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;

import com.example.myeventbus.databinding.ActivityMainBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
//        注册广播
        EventBus.getDefault().register(this);
//        跳转到发送页面
        binding.eventbusSend.setOnClickListener(view -> startActivity(new Intent(MainActivity.this, MainActivity2.class)));
//        发送粘性事件
        binding.eventbusSticky.setOnClickListener(view -> SendStickMsg());
    }

    //定义接受的方法
    @Subscribe(threadMode = ThreadMode.MAIN)  //主线程
    public void Msg(EventMessage eventMessage) {
        binding.text.setText(eventMessage.name);
    }
//    发送粘性事件的方法
    public void SendStickMsg(){
        EventBus.getDefault().postSticky(new StickMsg("这是粘性事件"));
        startActivity(new Intent(MainActivity.this,MainActivity2.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}